package com.ramos.kuaixiao.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.githang.statusbar.StatusBarCompat;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.MyView.SelfDialog;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.adapter.OrderItemAdapter;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.db.UnSubmitOrderDB;
import com.ramos.kuaixiao.entity.FindOrderDetail;
import com.ramos.kuaixiao.entity.OrderDetail;
import com.ramos.kuaixiao.entity.SendOrderDetail;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.FileUtil;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;
import com.ramos.kuaixiao.utils.Utils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class UnSubmitOrderDetailActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "UnSubmitOrderDetail";
    private Context mContext;
    private LinearLayout title_reback;
    private TextView title_text;
    private ListView mListView;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    private OrderItemAdapter mAdapter;
    private List<OrderDetail> productList = new ArrayList<>();
    TextView tv_salebillid;
    TextView tv_salebilldate;
    TextView tv_customer;
    TextView tv_selectck;
    TextView tv_shouhuoren;
    TextView tv_shouhuotel;
    TextView tv_shouhuodizhi;
    TextView tv_num;
    String orderId;
    Button b_submit;
    Button b_delete;
    FindOrderDetail findOrderDetail;
    UnSubmitOrderDB db = new UnSubmitOrderDB();
    CommonLoading loading;
    String storeHouseId;
    boolean isDMS =false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unsubmit_order_detail);
        mContext = this;
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.title), false);
        initView();
    }

    private void initView() {
        title_reback = (LinearLayout) findViewById(R.id.title_reback);
        title_reback.setOnClickListener(this);

        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("未完成订单详情");

        tv_salebilldate = (TextView) findViewById(R.id.tv_salebilldate);
        tv_customer = (TextView) findViewById(R.id.tv_customer);
        tv_selectck = (TextView) findViewById(R.id.tv_selectck);
        tv_shouhuoren = (TextView) findViewById(R.id.tv_shouhuoren);
        tv_shouhuotel = (TextView) findViewById(R.id.tv_shouhuotel);
        tv_shouhuodizhi = (TextView) findViewById(R.id.tv_shouhuodizhi);
        tv_num = (TextView) findViewById(R.id.tv_num);
        b_submit = (Button) findViewById(R.id.b_submit);
        b_delete = (Button) findViewById(R.id.b_delete);
        b_submit.setOnClickListener(this);
        b_delete.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.orderDetailListView);

        findOrderDetail = (FindOrderDetail) getIntent().getExtras().get("order");
        storeHouseId = findOrderDetail.getStoreHouseId();
        if (StringUtil.isEmpty(findOrderDetail.getHouseName())) {
            tv_salebilldate.setText(findOrderDetail.getCustmerName());
        } else {
            tv_salebilldate.setText(findOrderDetail.getHouseName());
        }
        if(!StringUtil.isEmpty(findOrderDetail.getDmsOrderId())){
            isDMS = true;
        } else {
            isDMS = false;
        }
        tv_customer.setText(findOrderDetail.getOrderDate());
        tv_selectck.setText(App.df.format(Double.valueOf(findOrderDetail.getOrderTotalPrice())));
        tv_shouhuoren.setText(findOrderDetail.getCommunicatePeople());
        tv_shouhuotel.setText(findOrderDetail.getTelephone());
        tv_shouhuodizhi.setText(findOrderDetail.getDstAddr());
        String orderlist = findOrderDetail.getOrderDetailList();
        if (StringUtil.isEmpty(orderlist)) {
            tv_num.setText("0件");
        } else {
            productList = JSONArray.parseArray(orderlist, OrderDetail.class);
            Log.d(TAG, "result " + productList.size());
            if (productList.size() > 0) {
                tv_num.setText(productList.size() + "件");
                mAdapter = new OrderItemAdapter(mContext, productList, storeHouseId, isDMS);
                mListView.setAdapter(mAdapter);
                Utils.setListViewHeightBasedOnChildren(mListView);
                Log.d(TAG, "result1 " + productList.size());
            } else {
                tv_num.setText("0件");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_reback:
                finish();
                break;
            case R.id.b_submit:
                submitOrder(findOrderDetail);
                break;
            case R.id.b_delete:
                deleteOrder(findOrderDetail);
                break;
            default:
                break;
        }
    }

    private void submitOrder(final FindOrderDetail findOrderDetail) {
        try {
            String url = NetUtils.INSERT_ORDER;
            loading = new CommonLoading(mContext);
            loading.setLoadText("提交订单中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setTimeout(30000);
            // 创建请求参数的封装的对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dealerId", findOrderDetail.getDealerId());
            jsonObject.put("orderSource", 2);
            jsonObject.put("phoneNum", FileUtil.getLineNum(this));
            jsonObject.put("versionName",  Utils.getVersionName(this));
            jsonObject.put("custmerId", findOrderDetail.getCustmerId());
            jsonObject.put("custmerName", findOrderDetail.getCustmerName());
            jsonObject.put("employerId",  findOrderDetail.getEmployerId());
            jsonObject.put("employerName", findOrderDetail.getEmployerName());
            jsonObject.put("businessId", findOrderDetail.getBusinessId());
            jsonObject.put("businessName",  findOrderDetail.getBusinessName());
            jsonObject.put("houseId", findOrderDetail.getHouseId());
            jsonObject.put("houseName", findOrderDetail.getHouseName());
            jsonObject.put("orderTotalPrice", findOrderDetail.getOrderTotalPrice());
            jsonObject.put("payType", typeToInt(findOrderDetail.getPayType()));
            jsonObject.put("deliveryType", typeToInt(findOrderDetail.getDeliveryType()));
            jsonObject.put("orderStatus", "SUBM");
            jsonObject.put("dstAddr", findOrderDetail.getDstAddr());
            jsonObject.put("telephone", findOrderDetail.getTelephone());
            jsonObject.put("comment", findOrderDetail.getComment());
            jsonObject.put("communicatePeople", findOrderDetail.getCommunicatePeople());
            jsonObject.put("orderDetailList",Utils.getJSONArray(findOrderDetail.getOrderDetailList()));
            Log.d(TAG, "order " + url);
            Log.d(TAG, "order " + jsonObject.toString());
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            //StringEntity stringEntity = new StringEntity(jsonObject.toString());
            // 执行post方法
            client.post(mContext, url, stringEntity, "application/json", new JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                    loading.dismiss();
                    Log.d(TAG, "order " + responseBody.toString());
                    try {
                        if (responseBody.getInt("status") == 200) {
                            updateStore(Utils.getList(findOrderDetail.getOrderDetailList()));
                            sendMessagea(UPLOAD_SUCCESS, responseBody.getString("msg"));
                        } else {
                            sendMessagea(UPLOAD_FAIL, responseBody.getString("msg"));
                        }
                    } catch (JSONException e) {
                        sendMessagea(UPLOAD_FAIL, "提交失败");
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    loading.dismiss();
                    sendMessagea(UPLOAD_FAIL, "提交失败");
                    throwable.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL, "提交失败");
            e.printStackTrace();
        }
    }

    private void updateStore(List<SendOrderDetail> list) {
        for(SendOrderDetail order : list){
            new StoreNumDB().updateNum(order.getProductInfoId(), order.getStoreHouseId(),order.getStoreHouseName(), order.getCalcParam(),order.getLargeUnitCount(), order.getSmallUnitCount());
        }
    }

    private int typeToInt(String s) {
        if (s.equals("货到付款")) {
            return 1;
        } else if (s.equals("在线支付")) {
            return 2;
        } else if (s.equals("信用贷款")) {
            return 3;
        } else if (s.equals("配送")) {
            return 1;
        } else if (s.equals("自提")) {
            return 2;
        } else if (s.equals("快递")) {
            return 3;
        } else {
            return 1;
        }
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    ToastUtils.showShort(mContext, "提交成功");
                    db.deleteUnSubmitOrder(findOrderDetail.getId());
                    finish();
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.showShort(mContext, msg.obj.toString()+"!请重新提交");
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }

    private void deleteOrder(final FindOrderDetail findOrderDetail) {
        final SelfDialog builder = new SelfDialog(this);
        builder.setTitle("删除未完成订单");
        builder.setMessage("是否删除未完成订单");
        builder.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                builder.dismiss();
            }
        });
        builder.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                if(db.deleteUnSubmitOrder(findOrderDetail.getId()) == 0){
                    ToastUtils.show("删除成功");
                    finish();
                }else {
                    ToastUtils.show("删除失败");
                }
                builder.dismiss();
            }
        });
        builder.show();
    }
}
